import Header from '../../components/Header'
import React, { useState, useReducer } from 'react'
import { InputItem, Button, Toast } from 'antd-mobile'
import './Login.less'
import { reqLogin } from '../../http/api'
//4. 存值---引入user里的initState,reducer
import { initState, reducer, actions } from './user'
export default function Login(props) {
    //1. 初始化数据
    const [user, setUser] = useState({
        phone: '',
        password: ''
    })
    // 5.整合
    const [state, dispatch] = useReducer(reducer, initState)
    //3. 点击登录按钮，发请求
    const gohome = () => {
        // 发请求
        reqLogin(user).then(res => {
            // 6.做逻辑
            if (res.data.code === 200) {
                // 6.1.弹成功
                Toast.success(res.data.msg)
                //6.2. 将用户信息存到仓库
                dispatch(actions.changeInfo(res.data.list))
                // 6.6 跳转到页面
                props.history.push('/index/home')
            }
        })

    }

    return (
        <div>
            <Header title="登录"></Header>
            {/*2. 绑定到页面 */}
            <div className="enter_user">
                <InputItem
                    clear
                    placeholder="123"
                    onChange={(val) => setUser({ ...user, phone: val })}
                >账号</InputItem>
                <InputItem
                    onChange={(val) => setUser({ ...user, password: val })}
                    clear
                    placeholder="123"
                >密码</InputItem>
                <Button onClick={() => gohome()} className="btn_login" type="primary" inline style={{ marginRight: '4px' }}>登录</Button>
                <div className="tologin" onClick={() => props.history.push('/register')}>
                    <span>还没有账号，去注册</span>
                </div>
            </div>
            <div>{JSON.stringify(user)}</div>
        </div>
    )
}

